﻿using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenXmlTools.OpenXML.Word;


namespace OpenXmlTools.OpenXML
{
    /// <summary>
    /// Word操作帮助类
    /// </summary>
    public static class OpenXMLWordHelper
    {
        /// <summary>
        /// 填充Word文档中的数据
        /// </summary>
        /// <param name="fileStream">Word文档流</param>
        /// <param name="replacements">替换字典（旧文本 -> 新文本）</param>
        /// <param name="tablesData">表格数据字典（表格索引或标识符 -> 行数据）</param>
        /// <param name="options">替换选项</param>
        /// <param name="identifierType">标识类型</param>
        /// <param name="tableDataStartRowIndex">表格数据起始行索引（行索引从0开始，默认为1，表示表格第一行为表头，数据从第二行开始）</param>
        /// <param name="useDefaultFormat">是否使用默认格式（边框：单实线，0.5磅，黑色；字体：宋体(中文)，Arial(ASCII字符字体)；内容居中对齐）</param>
        public static MemoryStream WriteData(Stream fileStream, Dictionary<string, string> replacements, Dictionary<string, List<List<string>>> tablesData,
            ReplaceTextOptions? options = null, WordTableIdentifierType identifierType = WordTableIdentifierType.None, int tableDataStartRowIndex = 1, bool useDefaultFormat = true)
        {
            try
            {
                options ??= new ReplaceTextOptions();

                // 创建文档的可写副本
                using var memoryStream = new MemoryStream();
                fileStream.CopyTo(memoryStream);
                memoryStream.Position = 0;
                fileStream.Position = 0;

                // 打开Word文档
                using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true))
                {
                    // 获取主文档部分
                    MainDocumentPart? mainPart = doc.MainDocumentPart;
                    if (mainPart != null)
                    {
                        // 替换Word文档中的文本内容
                        WordTextHelper.ReplaceText(mainPart, replacements, options);

                        // 填充Word文档中的表格数据
                        WordTableHelper.FillTables(mainPart, tablesData, identifierType, tableDataStartRowIndex, useDefaultFormat);

                        // 保存文档
                        mainPart.Document.Save();
                    }
                }

                // 重置流的读取/写入位置到起始点
                memoryStream.Position = 0;

                return memoryStream;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 填充Word文档中的数据，同时合并单元格
        /// </summary>
        /// <param name="fileStream">Word文档流</param>
        /// <param name="replacements">替换字典（旧文本 -> 新文本）</param>
        /// <param name="wordTables">表格数据集合</param>
        /// <param name="options">替换选项</param>
        /// <param name="identifierType">标识类型</param>
        /// <param name="tableDataStartRowIndex">表格数据起始行索引（行索引从0开始，默认为1，表示表格第一行为表头，数据从第二行开始）</param>
        /// <param name="useDefaultFormat">是否使用默认格式（边框：单实线，0.5磅，黑色；字体：宋体(中文)，Arial(ASCII字符字体)；内容居中对齐）</param>
        public static MemoryStream WriteData(Stream fileStream, Dictionary<string, string> replacements, List<WordTable> wordTables,
            ReplaceTextOptions? options = null, WordTableIdentifierType identifierType = WordTableIdentifierType.None, int tableDataStartRowIndex = 1, bool useDefaultFormat = true)
        {
            try
            {
                options ??= new ReplaceTextOptions();

                // 创建文档的可写副本
                using var memoryStream = new MemoryStream();
                fileStream.CopyTo(memoryStream);
                memoryStream.Position = 0;
                fileStream.Position = 0;

                // 打开Word文档
                using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true))
                {
                    // 获取主文档部分
                    MainDocumentPart? mainPart = doc.MainDocumentPart;
                    if (mainPart != null)
                    {
                        // 替换Word文档中的文本内容
                        WordTextHelper.ReplaceText(mainPart, replacements, options);

                        // 填充Word文档中的表格数据
                        WordTableHelper.FillTables(doc, wordTables, identifierType, tableDataStartRowIndex, useDefaultFormat);

                        // 保存文档
                        mainPart.Document.Save();
                    }
                }

                // 重置流的读取/写入位置到起始点
                memoryStream.Position = 0;

                return memoryStream;
            }
            catch (Exception)
            {
                throw;
            }
        }

    }
}
